package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.sys.models.dto.SysPermissionDTO;
import com.yt.sys.models.dto.SysRolePermissionDTO;
import com.yt.sys.models.service.ISysPermissionService;
import com.yt.sys.models.service.ISysRolePermissionService;
import com.yt.sys.models.vo.SysPermissionVO;
import com.yt.sys.models.vo.SysRolePermissionVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/sysRolePermission")
@Slf4j
@Api(value = "SysRolePermissionApiController", tags = "角色-权限关联信息Api接口")
public class SysRolePermissionApiController {

    @DubboReference
    private ISysRolePermissionService sysRolePermissionService;

    @DubboReference
    private ISysPermissionService sysPermissionService;

    @Data
    public static class RolePermissionBindBO {
        private Long roleId;
        private List<Long> permissionIds;
    }

    @ApiOperation(value = "角色绑定权限", notes = "为角色绑定多个权限")
    @PostMapping("/bind")
    public Result<RolePermissionBindBO> bindPermissions(@RequestBody RolePermissionBindBO bindBO) {
        // 1. 参数校验
        if (bindBO.getRoleId() == null || CollectionUtils.isEmpty(bindBO.getPermissionIds())) {
            return new Result<>(CodeEnum.FAIL_100002); // 参数错误
        }

        // 2. 权限ID合法性校验
        List<Long> permissionIds = bindBO.getPermissionIds();
        // 查询数据库中存在的权限ID
        List<SysPermissionDTO> existPermissions = sysPermissionService.selectBatchIds(permissionIds);
        List<Long> existIds = existPermissions.stream()
                .map(SysPermissionDTO::getId)
                .collect(Collectors.toList());

        // 检查是否有不存在的权限ID
        List<Long> invalidIds = permissionIds.stream()
                .filter(id -> !existIds.contains(id))
                .collect(Collectors.toList());

        if (!invalidIds.isEmpty()) {
            log.warn("角色绑定权限失败，存在无效权限ID: {}", invalidIds);
            return new Result<>(CodeEnum.FAIL_100011);
        }

        // 3. 查询当前角色已绑定的权限
        Wrapper<SysRolePermissionDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", bindBO.getRoleId());
        List<SysRolePermissionDTO> existingRelations = sysRolePermissionService.selectList(wrapper);
        List<Long> existingPermissionIds = existingRelations.stream()
                .map(SysRolePermissionDTO::getPermissionId)
                .collect(Collectors.toList());

        // 4. 计算需要新增和删除的权限ID
        List<Long> addIds = permissionIds.stream()
                .filter(id -> !existingPermissionIds.contains(id))
                .collect(Collectors.toList());
        List<Long> deleteIds = existingPermissionIds.stream()
                .filter(id -> !permissionIds.contains(id))
                .collect(Collectors.toList());

        // 5. 执行删除操作
        if (!deleteIds.isEmpty()) {
            Wrapper<SysRolePermissionDTO> deleteWrapper = new EntityWrapper<>();
            deleteWrapper.eq("role_id", bindBO.getRoleId())
                    .in("permission_id", deleteIds);
            sysRolePermissionService.delete(deleteWrapper);
        }

        // 6. 执行新增操作
        if (!addIds.isEmpty()) {
            List<SysRolePermissionDTO> addList = addIds.stream().map(permissionId -> {
                SysRolePermissionDTO dto = new SysRolePermissionDTO();
                dto.setRoleId(bindBO.getRoleId());
                dto.setPermissionId(permissionId);
                return dto;
            }).collect(Collectors.toList());
            sysRolePermissionService.insertBatch(addList);
        }

        return new Result<>(bindBO);
    }
    @ApiOperation(value = "角色解除权限绑定", notes = "解除角色与指定权限的绑定")
    @PostMapping("/unbind")
    public Result<Void> unbindPermissions(@RequestBody RolePermissionBindBO bindBO) {
        if (bindBO.getRoleId() == null || CollectionUtils.isEmpty(bindBO.getPermissionIds())) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        Wrapper<SysRolePermissionDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", bindBO.getRoleId())
                .in("permission_id", bindBO.getPermissionIds());

        boolean success = sysRolePermissionService.delete(wrapper);
        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100009);
    }

    @ApiOperation(value = "查询角色已绑定权限", notes = "查询指定角色已绑定的权限列表")
    @GetMapping("/get/{roleId}")
    public Result<List<SysPermissionVO>> getRolePermissions(@PathVariable Long roleId) {
        if (roleId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        // 查询角色绑定的权限ID
        Wrapper<SysRolePermissionDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", roleId);
        List<SysRolePermissionDTO> relationList = sysRolePermissionService.selectList(wrapper);

        // 查询权限详情
        List<Long> permissionIds = relationList.stream()
                .map(SysRolePermissionDTO::getPermissionId)
                .collect(Collectors.toList());

        List<SysPermissionDTO> permissionList = sysPermissionService.selectBatchIds(permissionIds);
        List<SysPermissionVO> voList = permissionList.stream().map(dto -> {
            SysPermissionVO vo = new SysPermissionVO();
            BeanUtils.copyProperties(dto, vo);
            return vo;
        }).collect(Collectors.toList());

        return new Result<>(voList);
    }

    @ApiOperation(value = "查询角色权限关联列表", notes = "分页查询角色权限关联记录（含角色名称和权限名称）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", defaultValue = "10", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/list")
    public Result<Page<SysRolePermissionVO>> list(
            Long roleId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        Map<String, Object> params = new HashMap<>();
        if (roleId != null) {
            params.put("roleId", roleId);
        }

        Page<SysRolePermissionVO> page = new Page<>(pageNum, pageSize);

        Page<SysRolePermissionVO> voPage = sysRolePermissionService.selectRolePermissionPage(page, params);

        return new Result<>(voPage);
    }
}